package com.turingoal.license.checker;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/**
 * 解密
 */
public final class TgLicenseDecryptUtil {
    private TgLicenseDecryptUtil() {
        throw new Error("工具类不能实例化！");
    }

    private static final Logger logger = LoggerFactory.getLogger(TgLicenseDecryptUtil.class); // 日志
    private static final int MAX_DECRYPT_BLOCK = 256; // RSA最大解密密文大小


    /**
     * <p>
     * 公钥解密
     * </p>
     *
     * @param encryptedData  已加密数据
     * @param publicKeyBytes 公钥
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, byte[] publicKeyBytes) {
        byte[] decryptedData = null;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicK);
            int inputLen = encryptedData.length;
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            decryptedData = out.toByteArray();
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | IOException | IllegalBlockSizeException | BadPaddingException e) {
            logger.debug("license解密失败！");
        }
        return decryptedData;
    }
}
